package com.comsoftstar.nt5s.Activity;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.hzc.nt5s.IConstant;
import com.hzc.nt5s.R;
import com.hzc.nt5s.deviceManager.bean.User;
import com.hzc.nt5s.deviceManager.preference.PreferencesUtil;
import com.hzc.nt5s.utils.Tools;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btn_login;
    private EditText userName;
    private EditText passWord;
    private Context mcontext;
    private ProgressDialog progressDialog;
    private CheckBox cb_remember_pwd;
    private LinearLayout activity_login;

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    activity,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mcontext = LoginActivity.this;

        initUI();
    }
    private void initUI(){
        btn_login= (Button) findViewById(R.id.btn_login);
        btn_login.setOnClickListener(this);
        userName=(EditText) findViewById(R.id.et_username);
        passWord=(EditText) findViewById(R.id.et_pwd);
        cb_remember_pwd=(CheckBox) findViewById(R.id.cb_remember_pwd);
        progressDialog = new ProgressDialog(mcontext);
        progressDialog.setCancelable(false);
        progressDialog.setMessage("正在登陆，请稍候");
        activity_login=(LinearLayout)findViewById(R.id.activity_login);
        activity_login.setOnClickListener(this);
        getSaveLoginInfo();                                                    //查看是有过记住密码
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_login:                        //登录
                progressDialog.show();                  //对话框
                if (userName.getText().toString().trim().equals("")) {
                    progressDialog.dismiss();
                    Tools.showToast(LoginActivity.this, "请输入用户名");
                } else if (passWord.getText().toString().trim().equals("")) {
                    progressDialog.dismiss();
                    Tools.showToast(LoginActivity.this, "请输入密码");
                } else {
                    // 登录方法
                    if (Tools.isNetAvailuable(mcontext)) {
                        login();
                    } else {
                        Tools.showToast(mcontext, "当前网络不可用，请检查网络");
                    }

                }
                break;
            case R.id.activity_login:               //关闭软键盘
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                break;
        }
    }
    //查看是有过记住密码
    private void getSaveLoginInfo() {
        String save = Tools.getSharedValue(mcontext, IConstant.FILE_USER, IConstant.SP_ISPWD_REMEMBER);
        if (save.equals("1")) {
            cb_remember_pwd.setChecked(true);
            passWord.setText(Tools.getSharedValue(mcontext, IConstant.FILE_USER, IConstant.SP_LOGIN_PWD));
            userName.setText(Tools.getSharedValue(mcontext, IConstant.FILE_USER, IConstant.SP_LOGIN_NAME));
        }
    }
//          登录数据请求判断
    private void login() {

            RequestParams params = new RequestParams(IConstant.URL+ "login");
            //params.setSslSocketFactory(...); // 设置ssl
            params.addBodyParameter("loginName", userName.getText().toString());
            params.addBodyParameter("Password", passWord.getText().toString());

//            System.out.println("请求的URL：" + params.toString());
//          xutils框架（登录检测账户密码）
            x.http().post(params, new Callback.CommonCallback<String>() {

                @Override
                public void onSuccess(String result) {
//           System.out.println("返回结果：" + result);
                    String results[] = result.split(":");
                    if (results[0].equals("1")) {
                        Tools.showToast(mcontext, "登录成功");

//USER配置文件更新
                        SharedPreferences sp = getSharedPreferences(IConstant.FILE_USER, Activity.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString(IConstant.SP_USERNAME, results[1]);
                        editor.commit();
//记住密码配置
                        if (cb_remember_pwd.isChecked()) {
                            Tools.setSharedValue(mcontext, IConstant.FILE_USER, IConstant.SP_LOGIN_NAME, userName.getText().toString());
                            Tools.setSharedValue(mcontext, IConstant.FILE_USER, IConstant.SP_LOGIN_PWD, passWord.getText().toString());
                            Tools.setSharedValue(mcontext, IConstant.FILE_USER, IConstant.SP_ISPWD_REMEMBER, "1");
                        } else {
                            Tools.setSharedValue(mcontext, IConstant.FILE_USER, IConstant.SP_LOGIN_NAME, "");
                            Tools.setSharedValue(mcontext, IConstant.FILE_USER, IConstant.SP_LOGIN_PWD, "");
                            Tools.setSharedValue(mcontext, IConstant.FILE_USER, IConstant.SP_ISPWD_REMEMBER, "0");
                        }
//                        userId = userName.getText().toString();
//                        progressDialog.setMessage("正在更新数据");
//                        progressDialog.show();
//PublicPreferences配置文件写入user=User的json数据  new Gson().toJson(user
                        User user= new User();
                        user.setUserName(userName.getText().toString());
                        user.setPassWord(passWord.getText().toString());
                        user.setName(results[1]);
                        PreferencesUtil.saveUser(LoginActivity.this, user);
                        startActivity(new Intent(mcontext, NT5SActivity.class));
                    } else {
                        progressDialog.dismiss();
                        Tools.showToast(mcontext, results[1]);
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    progressDialog.dismiss();
                    Tools.showToast(mcontext, "请求出错，请重试");
//                    System.out.println("出错：" + ex.getCause().toString());
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    progressDialog.dismiss();
                    Toast.makeText(mcontext, "cancelled", Toast.LENGTH_LONG).show();
                }

                @Override
                public void onFinished() {
                    progressDialog.dismiss();
                }
            });
        }
}
